'use strict';

const Controller = require('egg').Controller;

/**
 * @Controller 用户模块
 */

class UserController extends Controller {

  /**
      * @summary 获取用户信息
      * @description 获取个人信息
      * @router get /getInfo
      * @apikey
      * @response 200 baseResponse
      */
  async getInfo() {
    const { ctx } = this;
    return await ctx.service.user.getUserById();
  }

  /**
      * @summary 用户登录
      * @description 用户登录接口
      * @router post /login
      * @request body user *body
      * @response 200 baseResponse
      */
  async login() {
    const { ctx } = this;
    // 使用egg-swagger-doc字段验证规则
    ctx.validate(ctx.rule.user, ctx.request.body);
    const req = ctx.request.body;
    const rsp = await ctx.service.user.login(req);
    ctx.logger.info('获取返回值', rsp);
    if (rsp.code === 0) {
      const token = ctx.helper.generateToken(rsp.data.id, 60 * 1000 * 24);
      ctx.service.cache.set(rsp.data.id, token, 60 * 60);
      const res = rsp.data;
      const msg = rsp.msg;
      return ctx.helper.body.LOGIN_SUCCESS({ res, ctx, msg, token });
    }
    const msg = rsp.msg;
    return ctx.helper.body.VALIDATION_FAILED({ ctx, msg });

  }

  addUser() {
    const { ctx, app } = this;
    const rule = {
      username: { type: 'username' },
      password: { type: 'string' },
    };
    const err = app.validator.validate(rule, ctx.request.body);
    ctx.logger.warn('参数检查', err);
    if (err && err.length > 0) {
      const msg = err[0].message;
      return ctx.helper.body.VALIDATION_FAILED({ ctx, msg });
    }
    return ctx.service.user.addUser(ctx.request.body);
  }

  /**
      * @summary 用户列表查询
      * @description 用户列表查询接口
      * @router get /user
      * @apikey
      * @request query number *pageNo 页码
      * @request query number *pageSize 页数
      * @request query string gender 性别
      * @request query string phone 手机号
      * @request query string state 状态
      * @request query string country 城市
      * @request query string startTime 创建开始时间
      * @request query string endTime 创建结束时间
      * @response 200 baseResponse
      */
  async getUsers() {
    const { ctx } = this;
    // 使用egg-swagger-doc字段验证规则
    ctx.logger.info('======获取参数======', ctx.query);
    ctx.validate(ctx.rule.userSearch, ctx.query);
    const req = ctx.query;
    return await ctx.service.user.getUsers(req);

  }

}

module.exports = UserController;
